<template>
  <a-drawer
    v-bind="$attrs"
    :body-style="{ paddingBottom: '80px' }"
    :mask-closable="false"
    :destroy-on-close="true"
    @after-visible-change="onAfterVisibleChange"
    @close="onClose"
  >
    <a-spin :spinning="props.loading">
      <a-form layout="vertical">
        <a-form-item label="名称" v-bind="editFormValidateInfos.name">
          <a-input v-model:value="modelRef.name" placeholder="请输入应用名称" />
        </a-form-item>
        <a-form-item label="领域" v-bind="editFormValidateInfos.domain">
          <a-select v-model:value="modelRef.domain" placeholder="请选择应用领域">
            <a-select-option v-for="(option, idx) in selectOptions.domain" :key="idx" :value="option.name">
              {{ option.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="生命周期" v-bind="editFormValidateInfos.lifeCycle">
          <a-select v-model:value="modelRef.lifeCycle" placeholder="请选择应用生命周期">
            <a-select-option v-for="option in selectOptions.lifeCycle" :key="option.type" :value="option.type">
              {{ option.value }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="启用状态" v-bind="editFormValidateInfos.enable">
          <a-switch v-model:checked="modelRef.enable" />
        </a-form-item>
        <a-form-item label="描述" v-bind="editFormValidateInfos.description">
          <a-textarea v-model:value="modelRef.description" :rows="4" placeholder="请输入应用描述信息" />
        </a-form-item>
        <a-form-item label="图标" v-bind="editFormValidateInfos.icon">
          <a-upload
            v-model:file-list="uploadState.fileList"
            list-type="picture-card"
            class="avatar-uploader"
            :custom-request="handleCustomRequest"
            :before-upload="handleBeforeUpload"
            :max-count="1"
            @preview="handlePreview"
            @remove="handleRemove"
            @change="handleChange"
          >
            <div v-if="uploadState.fileList.length < 1" alt="avatar">
              <plus-outlined></plus-outlined>
              <div class="ant-upload-text">点击上传图标</div>
            </div>
          </a-upload>
          <div>请上传JPG/PNG格式、240*240px以上、1:1、2MB以内的无圆角图标</div>
          <a-modal
            :visible="uploadState.previewVisible"
            :title="uploadState.previewTitle"
            :footer="null"
            @cancel="handleCancel"
          >
            <img alt="example" style="width: 100%" :src="uploadState.previewImage" />
          </a-modal>
        </a-form-item>
      </a-form>
    </a-spin>
    <template #footer>
      <a-space>
        <a-button type="primary" @click.prevent="onSubmit">确定</a-button>
        <a-button @click="onClose">取消</a-button>
      </a-space>
    </template>
  </a-drawer>
</template>

<script lang="ts" setup>
import { reactive, ref, onBeforeMount, onMounted, onBeforeUnmount, onUnmounted, inject } from 'vue'
import { message, Form } from 'ant-design-vue'
import type { Rule } from 'ant-design-vue/es/form'
import { PlusOutlined } from '@ant-design/icons-vue'
import { getAppLifeCycleType, getAppDomainList } from '../factory'
import { appModel } from '../model'
import useUpload from '@/hooks/upload'
import { deepClone } from '@/utils/object'
import { isOverLength } from '@/utils/validate'

// const selectOptions = inject(provideSelectOptions, []) as any

const props = defineProps({
  loading: {
    type: Boolean,
    default: false,
  },
  current: {
    type: Object,
    default: () => {
      return deepClone(appModel)
    },
  },
})
const selectOptions = reactive({
  domain: [] as any,
  lifeCycle: [] as any,
})

const onAfterVisibleChange = (visible) => {
  let _app
  if (visible && props.current && props.current.id) {
    _app = deepClone(props.current)
    uploadState.fileList[0] = {
      thumbUrl: _app.iconUrl,
      url: _app.iconUrl,
      name: _app.icon,
    }
    console.log(_app)

    // _app.lifeCycle = selectOptions.lifeCycle.filter((item) => item.type === _app.lifeCycle)[0].key
  } else {
    _app = deepClone(appModel)
    uploadState.fileList = []
  }

  modelRef.value = _app

  if (props.loading) {
    emits('update:loading', false)
  }
}

const emits = defineEmits(['submit', 'update:visible', 'update:loading'])

let modelRef = ref(deepClone(appModel))
const rulesRef = reactive({
  name: [
    {
      required: true,
      message: '请输入广告名称',
    },
    {
      validator: async (_rule: Rule, value: string) => {
        if (isOverLength(value) > 50) {
          return Promise.reject('名称最大不能超过50个字符(中文算2字符)')
        } else {
          return Promise.resolve()
        }
      },
      trigger: 'change',
    },
  ],
  icon: [
    {
      required: true,
      message: '请上传应用图标',
    },
  ],
})

const handleChange = (info) => {
  if (info.file.status === 'done') {
    console.log(uploadState.fullName, ' done')
    modelRef.value.icon = uploadState.key
    if (info.file.type === 'image/jpeg') {
      uploadState.fileProcess = 'image/quality,Q_70/interlace,1'
    } else if (info.file.type === 'image/png') {
      uploadState.fileProcess = ' image/quality,Q_70format,jpg/interlace,1'
    }
    modelRef.value.fileProcess = uploadState.fileProcess
  }
}

const handleRemove = (file) => {
  uploadState.key = ''
  uploadState.fullName = ''
  uploadState.fileProcess = ''
  modelRef.value.fileProcess = uploadState.fileProcess
}

const {
  uploadState,
  handlePreview,
  handleCancel,
  // handleChange,
  handleBeforeUpload,
  // handleRemove,
  handleCustomRequest,
  handleReset,
} = useUpload('app')

const {
  resetFields: editFormResetFields,
  validate: editFormValidate,
  validateInfos: editFormValidateInfos,
} = Form.useForm(modelRef, rulesRef, {
  onValidate: (...args) => console.log(...args),
})
const onClose = () => {
  editFormResetFields()
  emits('update:visible', false)
}

const onSubmit = () => {
  editFormValidate()
    .then(() => {
      // form.data.img = uploadState.key
      // emits('submit', form.data)
      // modelRef.value.img = uploadState.key

      emits('submit', modelRef.value)
      console.log(modelRef.value)
      editFormResetFields()
      handleReset()
    })
    .catch((err) => {
      console.log('error', err)
    })
}
/**
 * 生命周期 onMounted
 */
onMounted(async () => {
  await getAppDomainList().then((res) => {
    if (res.data && res.data.length > 0) {
      selectOptions.domain = res.data
    }
  })
  await getAppLifeCycleType().then((res) => {
    if (res.data && res.data.length > 0) {
      selectOptions.lifeCycle = res.data
    }
  })
})
</script>
